package com.et.sale.deposit.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.et.common.time.DateUtil;
import com.et.sale.deposit.dao.DepositDao;
import com.et.sale.deposit.entity.DepositEntity;
import com.et.sale.deposit.service.DepositService;
import com.et.sale.member.dao.MemberDao;
import com.et.sale.member.entity.MemberEntity;
import com.et.sale.user.dao.UserDao;
import com.et.sale.user.entity.UserEntity;

@Service
public class DepositServiceImpl implements DepositService {

	@Autowired
	private DepositDao dao ;
	
	@Autowired
	private UserDao userDao ;
	
	@Autowired
	private MemberDao memberDao;
	
	
	
	
	/**
	 * 一定要有事务
	 */
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public int chongzhi(DepositEntity entity) {
		
		  int userId = entity.getUserId();
		  
		  //一：根据用户累计的充值金额得到用户的会员级别
		  
		  //得到累计充值金额
		  
		  Double preLeiji = dao.findTotalMoneyByUserId(userId);
		  if(null == preLeiji){
			  preLeiji = 0.0;
		  }
		  
		  Double totalMoney = preLeiji + entity.getMoney();
		  
		  
		  //二： 先得到会员的列表，再循环得到具体的会员级别
		  List<MemberEntity> memberList = memberDao.findAllMembers();
		  
		  
  		  //三： 把会员级别id设置到用户的 member_id字段
		  UserEntity user = userDao.findByUserId(userId);
		  
		  
		  for (int i = 0 ; i < memberList.size(); i++) {
			  MemberEntity member = memberList.get(i);
			  
			  System.out.println("循环次数" + i);
			  
			  //得到最小充值金额
			  Double minMoney = member.getMinMoney();
			  if(totalMoney >= minMoney){
				  user.setMemberId(member.getId());
				  break;
			  }else{
				  continue;
			  }
			
		  }
		  
		  
		  //1 根据userId找到用户对象 从中得到 balance属性
			
		  //2 从页面上会传过来充值的金额 money  那么 newBalance = balance +money
			Double newBalance =  user.getBalance() + entity.getMoney();
			
		  //3 把  newBalance 写回用户表即可
			Integer memberId = user.getMemberId();
			
			
			UserEntity user2 = new UserEntity();
			user2.setId(userId);
			user2.setBalance(newBalance);
			user2.setMemberId(memberId);
			
			userDao.update(user2);
			
		   //4 做正常的充值操作	
		   entity.setCreateDate(DateUtil.getDate());
		   return dao.add(entity);
	}

}
